<script setup lang="ts">
import { type ActionSheetAction, showConfirmDialog, showToast } from 'vant'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import b64ToBlob from 'b64-to-blob'
import { request } from '@/api'

interface IPickerParams {
  selectedValues: string[]
  selectedOptions: {
    text: string
    value: string
  }[]
  selectedIndexes: number[]
}
const profile = ref({} as JKYUser)

const xx = async () => {
  const user = await request.get('v1_0/user')
  profile.value.info = user.data.data.intro
}

onMounted(async () => {
  profile.value = await mqm.getUser()

  await xx()
  // Info.value = await mqm.updateInfo()
  console.log('profile  ----->  ', profile.value)
})

// 1. 修改头像
// 1.1 控制修改头像弹层的显示/隐藏
const isShowCamera = ref(false)
const onClickCamera = async (action: ActionSheetAction, index: number) => {
  if (index === 0) {
    const b64Str = await mqm.pickerCamera()
    console.log('xxxxx')
    uploadImg(b64Str)
  } else if (index === 1) {
    const b64Str = await mqm.pickerPhoto()
    console.log('hhhhh')
    uploadImg(b64Str)
  }
}

const uploadImg = async (b64str: string) => {
  isShowCamera.value = false
  try {
    const img = b64ToBlob(b64str)
    const fd = new FormData()
    fd.append('photo', img, Date.now() + '.jpeg')
    // showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    const res = await request.patch('v1_0/user/photo', fd)
    profile.value.photo = res.data.data.photo
    console.log('res  ----->  ', res)
    // mqm.updateUsr(Info)
    showToast('头像修改成功')
  } catch (err) {
    console.log('err  ----->  ', err)
    showToast('头像修改失败')
  }
}

const isShowGender = ref(false)
const sex = computed(() => {
  return profile.value.gender === 0 ? '男' : '女'
})
const onSelectGender = async (item: ActionSheetAction, i: number) => {
  isShowGender.value = false
  profile.value.gender = i
}

//选择生日

const updateBirthday = async () => {
  const res = await request.patch('v1_0/user/profile', { birthday: profile.value.birthday })
  console.log('res----->', res.data)
  showToast({ message: '更新成功' })
}

const isShowBirth = ref(false)
const onSelectBirth = async ({ selectedValues }: IPickerParams) => {
  profile.value.birthday = selectedValues.join('-')
  await updateBirthday()
  isShowBirth.value = false
}

const birthList = computed(() => {
  return profile.value.birthday.split('-').slice(0, 10)
})

const router = useRouter()
const goNickName = () => {
  router.push({
    path: '/nickname',
    query: {
      name: profile.value.name,
    },
  })
}

//退出登录
const isShowDialog = ref(false)
const fn = () => {
  showConfirmDialog({
    title: '温馨提示',
    message: '亲,您确定要退出吗？',
  })
    .then(() => {
      mqm.removeUser()
      isShowDialog.value = false
    })
    .catch(() => {
      isShowDialog.value = false
    })
}

const goUserInfo = () => {
  router.push({
    path: '/userinfo',
    query: {
      intro: profile.value.info,
    },
  })
}
</script>

<van-nav-bar title="标题" left-text="返回" left-arrow />
<template>
  <div class="colum-group">
    <van-cell-group>
      <van-cell title="头像" is-link @click="isShowCamera = true">
        <van-image round width="24" height="24" class="avatar-img" :src="profile.photo">
        </van-image>
      </van-cell>

      <van-field
        label="昵称"
        placeholder="未填写"
        input-align="right"
        right-icon="arrow"
        @click="goNickName"
        v-model="profile.name"
      >
        <!-- {{ profile.name }} -->
        <van-button round block type="primary"></van-button>
      </van-field>

      <van-field
        label="简介"
        placeholder="未填写"
        input-align="right"
        right-icon="arrow"
        @click="goUserInfo"
        v-model="profile.info"
      />
      <div class="space"></div>
      <van-field
        label="性别"
        readonly
        placeholder="未填写"
        input-align="right"
        right-icon="arrow"
        @click="isShowGender = true"
        v-model="sex"
      >
      </van-field>

      <van-field
        label="生日"
        readonly
        placeholder="请选择日期"
        input-align="right"
        right-icon="arrow"
        @click="isShowBirth = true"
        v-model="profile.birthday"
      ></van-field>
    </van-cell-group>

    <div class="submit">
      <van-button
        round
        block
        type="primary"
        to=""
        color="var(--mqm-MR)"
        v-model="isShowDialog"
        @click="fn"
      >
        退出登录
      </van-button>
    </div>

    <van-action-sheet
      v-model:show="isShowCamera"
      :actions="[{ name: '拍照' }, { name: '选择相册' }]"
      @select="onClickCamera"
      cancel-text="取消"
      :style="{ paddingBottom: '20px' }"
    />

    <VanActionSheet
      cancel-text="取消"
      v-model:show="isShowGender"
      :actions="[{ name: '男' }, { name: '女' }]"
      @select="onSelectGender"
      :style="{ paddingBottom: '20px' }"
    />

    <VanPopup title="选择生日" v-model:show="isShowBirth" position="bottom">
      <!-- 2. 回填生日到选择器 -->
      <VanDatePicker
        :model-value="birthList"
        @cancel="isShowBirth = false"
        @confirm="onSelectBirth"
        :min-date="new Date('1900-01-01')"
        :max-date="new Date()"
      />
    </VanPopup>
  </div>
</template>

<style lang="css" scoped>
.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mqm-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.colum-group {
  height: 44px;
  width: 100%;
  size: 16px;
  /* display: flex; */
}

.submit {
  width: 100%;
  height: 5%;
  padding: 16px;
  position: fixed;
  bottom: 60px;
  align-self: center;
  text-align: center;
}
.space {
  width: 100%;
  height: 12px;
  background-color: var(--mqm-N1);
}
.nav {
  width: 100%;
  height: 100px;
}
</style>
